package com.bodacn.storagescan;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class BaseRequest {
    private static final int REQUEST_TIMEOUT = 60 * 1000;//设置超时60秒
    public static final int HAND_REQUEST_SUCCESS = 300;
    public static final int HAND_REQUEST_FAILURE = 400;

    /**
     * post请求
     *
     * @param reqUrl
     * @param jsonParam json对象的String参数
     * @param handler   返回数据接收handler
     * @param type      返回请求类型
     */
    public static void postJsonData(final String reqUrl, final String jsonParam, @NonNull final Handler handler, final int type) {
            if (reqUrl == null) return;
            Log.d("BaseRequest","postJsonData请求地址：" + reqUrl);
            Log.d("BaseRequest","postJsonData请求参数：" + jsonParam);
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    BufferedReader reader = null;
                    try {
                        URL url = new URL(reqUrl);// 创建连接
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setDoOutput(true);
                        connection.setConnectTimeout(REQUEST_TIMEOUT);
                        connection.setDoInput(true);
                        connection.setUseCaches(true);
                        connection.setInstanceFollowRedirects(true);
                        connection.setRequestMethod("POST"); // 设置请求方式
                        connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
                        //设置发送数据长度（用于发送大量数据使用）
                        //connection.setRequestProperty("Content-Length", String.valueOf(jsonParam.length()));
                        //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
                        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                        out.append(jsonParam);
                        out.flush();
                        out.close();
                        Log.d("BaseRequest--1", String.valueOf(connection.getResponseCode()));
                        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            // 读取响应
                            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                            String line;
                            String res = "";
                            while ((line = reader.readLine()) != null) {
                                res += line;
                            }
                            Log.d("BaseRequest--2",res);
                            reader.close();
                            //通过handler来回传返回数据
                            Message msg = new Message();
                            msg.obj = res;
                            msg.arg1 = HAND_REQUEST_SUCCESS;
                            msg.what = type;
                            handler.sendMessage(msg);
                        } else {
                            Message msg = new Message();
                            msg.obj = "请求错误," + connection.getResponseCode();
                            msg.arg1 = HAND_REQUEST_FAILURE;
                            msg.what = type;
                            handler.sendMessage(msg);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Message msg = new Message();
                        msg.obj = "请求异常,请检查网络";
                        msg.arg1 = HAND_REQUEST_FAILURE;
                        msg.what = type;
                        handler.sendMessage(msg);
                        Log.e("POST IOException", e.getMessage());
                    } finally {
                        System.out.println("postJsonData:Close;");
                        if(reader!=null){
                            try{
                                System.out.println("postJsonData:Close-1");
                                reader.close();
                                System.out.println("postJsonData:Close-2");
                            }catch (IOException e){
                                throw new RuntimeException("postJsonData-关闭失败");
                            }
                        }
                    }
                }
            }.start();
    }


    public static void getData(final String getUrl, final Handler handler, final int type) {
        Log.d("BaseRequest","getData请求地址：" + getUrl);
        new Thread() {
            @Override
            public void run() {
                super.run();
                String acceptData = "";
                try {
                    URL url = new URL(getUrl);// 创建连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(REQUEST_TIMEOUT);
                    connection.setRequestMethod("GET"); // 设置请求方式
                    connection.connect();
                    Log.d("BaseRequest", String.valueOf(connection.getResponseCode()));
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        //Log.i("接受到的数据：", String.valueOf(connection.getResponseCode()));
                        InputStream inputStream = connection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                        String line;
                        while ((line = bufferedReader.readLine()) != null) { //不为空进行操作
                            acceptData += line;
                        }
                        Log.d("BaseRequest",acceptData);
                        if (handler != null) {
                            Message msg = new Message();
                            msg.obj = acceptData;
                            msg.arg1 = HAND_REQUEST_SUCCESS;
                            msg.what = type;
                            handler.sendMessage(msg);
                        }
                    } else {
                        Message msg = new Message();
                        msg.obj = "请求错误," + connection.getResponseCode();
                        msg.arg1 = HAND_REQUEST_FAILURE;
                        msg.what = type;
                        handler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.obj = "请求异常,请检查网络";
                    msg.arg1 = HAND_REQUEST_FAILURE;
                    msg.what = type;
                    handler.sendMessage(msg);
                    Log.d("BaseRequest","GET IOException", e);
                }
            }
        }.start();
    }
}
